/*
 *	Copyright (c) 2013, Yulong Information Technologies
 *	All rights reserved.
 *  
 *  @Project: Db
 *  @author: Robot
 *	@email: feng88724@126.com
 */
package com.example.db.core;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author Robot
 * @weibo http://weibo.com/feng88724
 * @date Apr 10, 2013	
 */
public class DBConfig {
	
	private static String DATABASE_NAME = "test.db";
	private static int DATABASE_VERSION = 1;
	private static Context mContext = null;
	public static final Set<Class<?>> models = new HashSet<Class<?>>();
	
	/**
	 * 增加数据表(在init()之前调用有效)
	 * @param model
	 */
	public static void addModel(Class<?> model) {
		models.add(model);
	}
	
	/**
	 * 初始化
	 * 默认数据库名
	 * 默认数据库版本
	 * @param context
	 */
	public static void init(Context context) {
		init(context, DATABASE_NAME, DATABASE_VERSION, null);
	}
	
	/**
	 * 初始化
	 * 默认数据库名
	 * 默认数据库版本
	 * @param tables	
	 * @param context
	 */
	public static void init(Context context, List<Class<?>> tables) {
		init(context, DATABASE_NAME, DATABASE_VERSION, tables);
	}
	
	/**
	 * 初始化
	 * @param context	
	 * @param dbName		数据库名
	 * @param dbVersion		数据库版本
	 * @param tables		数据表实体
	 */
	public static void init(Context context, String dbName, int dbVersion, List<Class<?>> tables) {
		if(context == null)
			throw new NullPointerException("Context cannot be null");
		DBConfig.DATABASE_NAME = dbName;
		DBConfig.DATABASE_VERSION = dbVersion;
		DBConfig.mContext = context;
		if(tables != null)
			for (Class<?> clazz : tables) {
				addModel(clazz);
			}
		dbHelper = new DatabaseHelper(DBConfig.mContext, DATABASE_NAME, null, DATABASE_VERSION);
		database = dbHelper.getWritableDatabase();
	}
	
	private volatile static SQLiteOpenHelper dbHelper;
	private volatile static SQLiteDatabase database;
	
	/**
	 * @return the dbHelper
	 */
	public static SQLiteOpenHelper getDbHelper() {
		return dbHelper;
	}

	/**
	 * @return the database
	 */
	public static SQLiteDatabase getDatabase() {
		if(database == null) {
			throw new IllegalArgumentException("database cannot be null");
		}
		return database;
	}
}
